/**
 * 
 */
package denaris.core.controller;

import java.util.Vector;

import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.Sprite;

import denaris.factory.FrameFactory;
import denaris.factory.ImageFactory;

/**
 * @author stkl23
 *
 */
public class ExplosionController extends AbstractController {
	/** the explosions frame sequence is static as it is shared by all explosions */
	public static final int[] EXPLOSION = FrameFactory.createSequence(0, 6, 2);
	/** the static explosion image is also shared by all sprites */
	private static final Image EXPLOSION_IMAGE = ImageFactory.getImage("/denaris/resource/sprite/explosion.png");
	/** We'll cache the explosion sprites*/
	private static Vector cache = new Vector(25);
	/** do not cache more than 50 simultaneous explosions*/
	private static final int MAX_CACHE_SIZE = 50;
	
	public ExplosionController(int x, int y) {
		super();
		Sprite cachedSprite = getCachedSprite();
		// set the position
		cachedSprite.setPosition(x, y);
		// set the explosion sprite
		setSprite(cachedSprite);
	}
	
	/** returns the next Sprite from the cache or creates a new one if necessary. */
	private static Sprite getCachedSprite() {
		for (int i=0; i<cache.size(); i++) {
			Sprite s = (Sprite) cache.elementAt(i);
			if (!s.isVisible()) {
				// return this sprite - it's not used
				s.setVisible(true);
				return s;
			}
		}
		
		Sprite sprite = new Sprite(EXPLOSION_IMAGE, 18, 16);
		sprite.setVisible(true);
		// create the frame sequence
		sprite.setFrameSequence(EXPLOSION);
		if (cache.size() < MAX_CACHE_SIZE) {
			// the cache cannot provide a new explosion sprite so we must create a new one
			// put it in the cache
			cache.addElement(sprite);
		}
		return sprite;
	}
	
	/* (non-Javadoc)
	 * @see denaris.core.AbstractController#advance()
	 */
	public boolean advance() {
		// animate in case there is a frame sequence
		if (controllable.getFrameSequenceLength() > 0) {
			controllable.nextFrame();
			if (controllable.getFrame() == controllable.getFrameSequenceLength() - 1) {
				return false;
			}
		}
		return true;
	}
}
